package com.h2cloud.TestException;

/**
 * @Package: PACKAGE_NAME
 * @ClassName: test
 * @Author: h2cloud
 * @CreateTime: 2021/8/15 1:17 上午
 * @Description:
 */
public class test {
	// 情况一：catch、finally中都没有 return 语句
	// 正常执行，返回 try中的 return；  输出 try,
	// 出现异常：出现异常处的代码，前面的代码正常执行。最后返回 最后一行的 return
	// a处出现异常，输出：getValue2() = catch,finally,last return.
	// b处出现异常，输出：getValue2() = try,catch,finally,last return.
	public static String getValue2() {
		StringBuilder sb = new StringBuilder();

		try {
			// int a = 1 / 0; // a处出现异常
			sb.append("try,");
			int b = 1 / 0; // b出现异常
			System.out.println("try block: " + sb.toString());
			return sb.toString();

		} catch (Exception e) {
			sb.append("catch,");
			System.out.println("catch block: " + sb.toString());

		} finally {
			sb.append("finally,");
			System.out.println("finally block: " + sb.toString());

		}
		return sb.append("last return.").toString();
	}

	// 情况二：catch、finally中的 return都会覆盖 try中的 return【无论有无发生异常】
	public static String getValue3() {
		StringBuilder sb = new StringBuilder();

		try {
			// int a = 1 / 0;
			sb.append("try,");
			int b = 1 / 0;
			System.out.println("try block: " + sb.toString());
			return sb.toString();

		} catch (Exception e) {
			sb.append("catch,");
			System.out.println("catch block: " + sb.toString());
			return sb.toString();

		} finally {
			// 如果没有 catch, 在 finally中 return，会吞掉 try中的异常
			sb.append("finally,");
			System.out.println("finally block: " + sb.toString());
			return sb.toString();

		}
	}

	// 情况二：catch、finally中的 return都会覆盖 try中的 return
	public static String getValue3_2() {
		StringBuilder sb = new StringBuilder();

		try {
			// int a = 1 / 0;
			sb.append("try,");
			// int b = 1 / 0;
			System.out.println("try block: " + sb.toString());
			return sb.toString();

		} catch (Exception e) {
			sb.append("catch,");
			System.out.println("catch block: " + sb.toString());
			return sb.toString();

		} finally {
			// 如果没有 catch, 在 finally中 return，会吞掉 try中的异常
			sb.append("finally,");
			System.out.println("finally block: " + sb.toString());
			return "3";

		}
	}


	// 情况三：在 finally中修改 try中的返回值，
	// 分 基本数据类型（不会被修改） 和 引用数据类型（会被修改） 两种情况
	public static int getValue4() {
		int a = 10;
		try {
			return a;
		} finally {
			a = 100;
		}
	}

	public static student getValue5() {
		student st = new student();
		try {
			return st;
		} finally {
			st.age = 100;
		}
	}

	static class student {
		int age = 10;
	}

	public static void main(String[] args) {
		// System.out.println("getValue2() = " + getValue2());
		// System.out.println("getValue3() = " + getValue3());
		System.out.println("getValue3_2() = " + getValue3_2());
		// System.out.println("getValue4() = " + getValue4());
		// System.out.println("getValue5() = " + getValue5().age);
	}
}
